import { defineStore } from 'pinia';
import { ref } from 'vue';
import { configKey } from '@/api/earlyWarning';
import {
  getSurroundingResource,
  getWarningInfo,
  getWeatherInfo,
  getMonitorDeviceTree,
  getGisList,
  getSurroundingVideo,
  deleteAreHandler,
  getResourcesTree,
  getDisposalPlan
} from '@/api/Assist';
import { useConcentrationPoint } from '@/hooks/useConcentrationPoint';
import { useCesiumPoints } from '@/hooks/useCesiumPoints';

export interface WarningInfo {
  createTime?: string;
  durationTime?: string;
  occurrenceAddress?: string;
  reportUser?: string;
  reportTel?: string;
  liabilityCompany?: string;
  liabilityUser?: string;
  liabilityUserPhone?: string;
  waringContent?: string;
  longitude?: string;
  latitude?: string;
}

export interface WeatherData {
  temp: string;
  humidity: string;
  pressure: string;
  windDirection: string;
  windPower: string;
  rainfall: string;
}

interface IGisList {
  valves: any;
  trans: any;
  concentrations: any;
}

interface IPlan {
  code?: string;
  files?: string;
  id?: string;
  imageUrl?: string;
  name?: string;
  ossIds?: string;
  path?: string;
  planContent?: string;
  planOssId?: string;
  planOssIds?: string;
  waringId?: string;
  warningLevel?: string;
}

export const useAssistStore = defineStore('assist', () => {
  const { clearAllPoints, loadCircle } = useCesiumPoints();
  const { drawConcentrationPoints, drawArea } = useConcentrationPoint();

  const sliderValue = ref<number>(0);
  const warningInfo = ref<WarningInfo>({
    createTime: '',
    durationTime: '',
    occurrenceAddress: '',
    reportUser: '',
    reportTel: '',
    liabilityCompany: '',
    liabilityUser: '',
    liabilityUserPhone: '',
    waringContent: '',
    latitude: '',
    longitude: ''
  });
  const weatherData = ref<WeatherData>({
    temp: '',
    humidity: '',
    pressure: '',
    windDirection: '',
    windPower: '',
    rainfall: ''
  });
  const resourceData = ref([]); //周边资源数据源
  const dataMonitoringResource = ref([]); //数据资源

  const resourcesTreeData = ref([]); //资源树

  const currentWarningId = ref('');

  const gisList = ref<IGisList>({
    valves: [],
    trans: [],
    concentrations: []
  });
  const concentrationDataSource = ref([]);
  const areaDataSource = ref({});
  const surroundingVideoData = ref<any>([]);

  const loadingInstance = ref(null);

  const searchValue = ref('');

  const disposalPlan = ref<IPlan>({});
  const params = computed(() => {
    return {
      waringId: currentWarningId.value,
      distance: sliderValue.value / 1000,
      queryName: searchValue.value
    };
  });
  const getDistance = async () => {
    const { data } = await configKey('distance');
    sliderValue.value = Number(data) * 1000;
  };
  //滑块更改事件
  const sliderChange = async (value: number) => {
    try {
      sliderValue.value = value;
      loadingInstance.value = ElLoading.service({ text: '正在加载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' });
      await getDataMonitoringResourceHandle();
      await getSurroundingResourceHandle();
      await getGisListHandle();
      await getSurroundingVideoHandle();
      await getResourcesTreeHandle();
    } catch (error) {
      console.log(error);
    } finally {
      loadingInstance.value.close();
      loadCircle(warningInfo.value, sliderValue.value);
    }
  };
  //获取预警信息模块数据
  const getWarningInfoHandle = async () => {
    const { data } = await getWarningInfo(currentWarningId.value);
    warningInfo.value = data;
  };
  //获取天气模块数据
  const getWeatherInfoHandle = async () => {
    const { data } = await getWeatherInfo(currentWarningId.value);
    weatherData.value = data;
  };
  //获取周边资源列表
  const getSurroundingResourceHandle = async () => {
    const { data } = await getSurroundingResource(params.value);
    resourceData.value = data;
  };
  //获取数据监测资源
  const getDataMonitoringResourceHandle = async () => {
    const { data } = await getMonitorDeviceTree(params.value);
    dataMonitoringResource.value = data;
  };
  //获取首页Gis列表
  const getGisListHandle = async () => {
    const { data } = await getGisList({ warningId: currentWarningId.value });
    gisList.value = data;
    await addConcentrationPoint();
    await addArea();
  };
  //获取资源树的数据
  const getResourcesTreeHandle = async () => {
    const { data } = await getResourcesTree(params.value);
    resourcesTreeData.value = data;
  };
  //添加浓度点位方法
  const addConcentrationPoint = async () => {
    if (concentrationDataSource.value?.length > 0) {
      clearAllPoints(concentrationDataSource.value);
      concentrationDataSource.value = [];
    }
    concentrationDataSource.value = gisList.value.concentrations?.map((point) => drawConcentrationPoints(point));
  };
  //添加区域点位的方法
  const addArea = async () => {
    for (const key in gisList.value) {
      if (key !== 'concentrations' && key !== 'valves' && key !== 'trans') {
        if (Object.keys(areaDataSource.value).length > 0) {
          if (areaDataSource.value[key] && areaDataSource.value[key].length > 0) {
            clearAllPoints(areaDataSource.value[key]);
            delete areaDataSource.value;
          }
        }
        if (gisList.value[key]) {
          areaDataSource.value[key] = gisList.value[key].map((point) => drawArea(point));
        }
      }
    }
  };
  //删除区域的方法
  const removeArea = async (id: string) => {
    const { code } = await deleteAreHandler(id);
    if (code === 200) {
      await getGisListHandle();
    }
  };
  //删除浓度点位方法
  const removeConcentrationPoint = async (id: string) => {
    const { code } = await deleteAreHandler(id);
    if (code === 200) {
      await getGisListHandle();
    }
  };
  //获取视频树数据
  const getSurroundingVideoHandle = async () => {
    const { data } = await getSurroundingVideo({
      waringId: currentWarningId.value,
      distance: sliderValue.value
    });
    surroundingVideoData.value = data;
  };
  //获取处置预案
  const getDisposalPlanHandle = async () => {
    const { data } = await getDisposalPlan({
      waringId: currentWarningId.value
    });
    disposalPlan.value = data;
  };
  const resetStore = () => {
    currentWarningId.value = '';
    sliderValue.value = 0;
    warningInfo.value = {
      createTime: '',
      durationTime: '',
      occurrenceAddress: '',
      reportUser: '',
      reportTel: '',
      liabilityCompany: '',
      liabilityUser: '',
      liabilityUserPhone: '',
      waringContent: '',
      latitude: '',
      longitude: ''
    };
    weatherData.value = {
      temp: '',
      humidity: '',
      pressure: '',
      windDirection: '',
      windPower: '',
      rainfall: ''
    };
    resourceData.value = [];
    resourcesTreeData.value = [];
    dataMonitoringResource.value = [];
    gisList.value = {
      valves: [],
      trans: [],
      concentrations: []
    };
    concentrationDataSource.value = [];
    areaDataSource.value = {};
    surroundingVideoData.value = [];
    loadingInstance.value = null;
    searchValue.value = '';
    disposalPlan.value = {};
  };
  onMounted(async () => {
    await getDistance();
  });
  onUnmounted(() => {
    resetStore();
  });
  watch(
    currentWarningId,
    async () => {
      if (!currentWarningId.value) return;
      try {
        loadingInstance.value = ElLoading.service({ text: '正在加载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' });
        await getWarningInfoHandle();
        await getWeatherInfoHandle();
        await getDataMonitoringResourceHandle();
        await getSurroundingResourceHandle();
        await getSurroundingVideoHandle();
        await getGisListHandle();
        await getDisposalPlanHandle();
        await getResourcesTreeHandle();
      } catch (error) {
        console.warn(error, '获取资源失败');
      } finally {
        loadingInstance.value.close();
        loadCircle(warningInfo.value, sliderValue.value);
      }
    },
    {
      immediate: true
    }
  );
  return {
    sliderValue,
    warningInfo,
    weatherData,
    resourceData,
    dataMonitoringResource,
    gisList,
    surroundingVideoData,
    currentWarningId,
    resourcesTreeData,
    searchValue,
    disposalPlan,
    getGisListHandle,
    getResourcesTreeHandle,
    removeConcentrationPoint,
    removeArea,
    sliderChange
  };
});
